package com.jpm.jrogue
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.text.TextField;
	import flash.utils.getDefinitionByName;
	
	/**
	 * ...
	 * @author Jonboy
	 */
	[SWF(width="1200",height="700",frameRate="60",backgroundColor="#000000")]
	public class Preloader extends MovieClip
	{
		
		private static const PROGRESS_BAR_HEIGHT:Number = 20;
		private var text:TextField = new TextField();
		
		public function Preloader()
		{
			if (stage)
			{
				stage.scaleMode = StageScaleMode.NO_SCALE;
				stage.align = StageAlign.TOP_LEFT;
			}
			addEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
		
			
			text.textColor = 0xFFFFFF;
			text.text = "Loading..."
			text.y = stage.stageHeight - 100;
			text.x = stage.stageWidth / 2 - "Loading...".length / 2;
			addChild(text);
		}
		
		private function ioError(e:IOErrorEvent):void
		{
			trace(e.text);
		}
		
		private function progress(event:ProgressEvent):void
		{
			graphics.clear();
			graphics.beginFill(0xcccccc);
			graphics.drawRect(0, (stage.stageHeight - PROGRESS_BAR_HEIGHT) / 2, stage.stageWidth * event.bytesLoaded / event.bytesTotal, PROGRESS_BAR_HEIGHT);
			graphics.endFill();
		}
		
		private function checkFrame(e:Event):void
		{
			if (currentFrame == totalFrames)
			{
				stop();
				loadingFinished();
			}
		}
		
		private function loadingFinished():void
		{
			removeEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			// TODO hide loader
			removeChild(text);
			graphics.clear();
			startup();
		}
		
		private function startup():void
		{
			var mainClass:Class = getDefinitionByName("com.jpm.jrogue.Main") as Class;
			addChild(new mainClass() as DisplayObject);
		}
	
	}

}